// miniprogram/pages/admin/product/addProduct.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    category: '',
    categoryRange: ["水果"],
    sellUnitRange: ["KG","个","袋","盒","件"],
    sellUnit: '',
    images: [], // 商品图片
    formData: {

    },
    attrList:[],
    rules: [
        {
            name: 'name',
            rules: {required: true, message: '商品名称必填'},
        },
        {
            name: 'weight',
            rules: {required: true, message: '商品重量必填'},
        },
        {
            name: 'upcCode',
            rules: {required: true, message: '商品条码必填'},
        },
        {
            name: 'sellPrice',
            rules: {required: true, message: '商品售价必填'},
        },
        {
            name: 'sellUnit',
            rules: {required: true, message: '销售单位必填'},
        },
        {
            name: 'category',
            rules: {required: true, message: '商品分类必填'},
        },
        {
            name: 'deliverMoney',
            rules: {required: true, message: '商品运费必填'},
        },
    ]
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData();
    /**必须配置，否则无法回调该函数 */
    this.setData({
        selectFile: this.selectFile.bind(this),
        uplaodFile: this.uplaodFile.bind(this),
        deleteHander: this.deleteHander.bind(this),
        slideButtons: [{
            type: 'warn',
            text: '删除',
            extClass: 'slideBtnClass',
            src: '/page/weui/cell/icon_del.svg', // icon的路径
        }]
    });
  },
  initData() {
    const that = this;
    // 获取类目
    wx.cloud.callFunction({
      // 需调用的云函数名
      name: 'categoryApi',
      // 传给云函数的参数
      data: {
        method: "queryList",
        args: {}
      },complete: (res)=>{
        that.setData({
          categoryRange: res.result.rstData.data
        });
      }
    });
  },
  /**
     * 删除图片回调函数 
     * detail = {index, item:{flag:true, url:''}}
     * index为下标，item为图片对象
    */
   deleteHander: function(e) {
        let dto = e.detail;
        let url = dto.item.url;
        wx.cloud.deleteFile({
        fileList: [url],
        success: res => {
            console.log('删除成功',res.fileList)
        },
        fail: console.error
        })
   },
   /**表单输入处理函数 */
  formInputChange(e) {
      //console.log(this,"这是this")
      const {field} = e.currentTarget.dataset
      this.setData({
          [`formData.${field}`]: e.detail.value
      })
  },
  /**选择商品销售单位处理函数 */
  bindSelectUnitChange(e) {
    const {field} = e.currentTarget.dataset
    const index = Number(e.detail.value);
    let val = this.data.sellUnitRange[index]
    this.setData({
        sellUnit: val,
        [`formData.${field}`]: val
    })
  },
  /**选择商品品类处理函数 */
  bindSelectSortChange(e) {
    console.log(e,"选择品类")
    const {field} = e.currentTarget.dataset
    const index = Number(e.detail.value);
    let itemObj = this.data.categoryRange[index];
    this.setData({
        category: itemObj.name,
        [`formData.${field}`]: itemObj.name,
        [`formData.${field}Id`]: itemObj._id
    })
  },
  /**表单提交函数 */
  submitForm() {
        if(this.data.attrList.length === 0) {
            wx.showToast({
                title: '商品属性必填',
                icon: "none",
                duration: 2000
            });
            return;   
        }
        for(let item of this.data.attrList) {
            if(!item.attrName || !item.attrStk) {
                wx.showToast({
                    title: '请填写商品属性库存和名称',
                    icon: "none",
                    duration: 2000
                });
                return;  
            }
        }
        this.selectComponent('#form').validate((valid, errors) => {
            console.log('valid', valid, errors)
            if (!valid) {
                wx.showToast({
                    title: errors[0].message,
                    icon: "none",
                    duration: 2000
                })
            } else {
              console.log("表单数据：", 
              this.data.formData, 
              this.data.attrList, 
              this.data.images);
              let dto = this.data.formData;
              dto.images = this.data.images;
              dto.status = '已上架';
              dto.sumStk = this.data.attrList.reduce((pre, cur) => {
                  return Number(cur.attrStk) + pre;
              }, 0);
              dto.sellNum = 0;
              dto.attr = this.data.attrList.map(item => {
                  let newItem = {};
                  newItem.attrName = item.attrName;
                  newItem.attrStk = Number(item.attrStk);
                  return newItem;
              });
              this.saveProduct(dto);
            }
        });
  },
  /**选择图片函数 */
  selectFile(files) {
    console.log('files', files)
    // 返回false可以阻止某次文件上传
    return true;
  },
  /**上传图片函数 */
  uplaodFile(files) {
        const that = this;
        // 文件上传的函数，返回一个promise
        return new Promise((resolve, reject) => {
            var successUrl = [];
            let tempFilePathArr = files.tempFilePaths;
            for(let tempFile of tempFilePathArr) {
                console.log('tempFilePaths=', files);
                wx.cloud.uploadFile({
                    cloudPath:"product/" + new Date().getTime()+'.png',
                    filePath: tempFile,
                    success: res => {
                        console.log("上传成功", res);
                        that.data.images.push(res.fileID);
                        resolve({urls: [res.fileID]});
                    }
                }) 
            } 
        })
    },
    /**上传失败回调函数 */
    uploadError(e) {
        console.log('upload error', e.detail)
    },
    /**上传成功回调函数 */
    uploadSuccess(e) {
        console.log('upload success', e.detail)
    },
    /**添加属性按钮 */
    addAttrBtn(e) {
        if(this.data.attrList.length > 4) {
            wx.showToast({
                title: '最多添加5个属性',
                icon: 'error',
                duration: 2000
              });
            return;
        }
        this.data.attrList.push({id: new Date().getTime()});
        this.setData({
            attrList: this.data.attrList
        });
    },
    /**属性与库存输入处理函数 */
    attrInputHander(e) {
        console.log("库存数处理", e)
        const index = e.currentTarget.dataset.index;
        const field = e.currentTarget.dataset.field;
        this.data.attrList[index][field] = e.detail.value;
        console.log(this.data.attrList)
    },
    /**滑动删除事件处理 */
    slideButtonTap(e) {
        console.log(e,"滑懂删除")
        const index = e.currentTarget.dataset.index;
        const id = e.currentTarget.dataset.id;
        const temp = this.data.attrList.filter(item => item.id != id);
        this.setData({
            attrList: temp
        });
        console.log(this.data.attrList)
    },
    saveProduct(dto) {
        // 保存产品
        wx.cloud.callFunction({
            // 需调用的云函数名
            name: 'productapi',
            // 传给云函数的参数
            data: {
              method: "save",
              args: dto
            },complete: (res)=>{
                console.log(res,"类目")
                wx.showToast({
                    title: '保存成功'
                })
            }
        });
    }
})